package cheesymock;

import java.lang.reflect.*;

import cheesymock.recorder.RecorderMock;


/**
 * Factory object that creates new proxies using the JDK Dynamic Proxy
 * mechanism.
 *
 * @author fredrik
 */
public class SimpleProxyFactory implements ProxyFactory {

	public Object newProxy(Class<?> clazz, Validator[] validators, Object delegate,
			DefaultReturn defaultReturn) {
		SimpleMock mock = new SimpleMock(clazz, validators, delegate, defaultReturn);
		try {
		    return Proxy.newProxyInstance(clazz.getClassLoader(),
					new Class<?>[] { clazz }, mock);
		}
		catch (ExceptionInInitializerError eiie) {
			throw new RuntimeException(eiie);
		}
	}

	public Object getHandler(Object proxy) {
		return Proxy.getInvocationHandler(proxy);
	}

	public Object newRecorderProxyFromProxy(Object proxy, RecorderMock mock) {
		final Class<?> clazz = proxy.getClass();
		final Class<?>[] interfaces = clazz.getInterfaces();
		try {
		    return Proxy.newProxyInstance(clazz.getClassLoader(),
		    		interfaces, mock);
		}
		catch (ExceptionInInitializerError eiie) {
			throw new RuntimeException(eiie);
		}
	}
}